//
//  SNUpdateClass.m
//  project
//
//  Created by 黄建华 on 2017/12/30.
//  Copyright © 2017年 黄建华. All rights reserved.
//

#import "SNUpdateClass.h"
#import "AFNetworking.h"
#import "YYJSONHelper.h"
#import "MKNetworkKit.h"
#import "JSON.h"
#import "FileModelEntity.h"
@implementation SNUpdateClass

DEF_SINGLETON(SNUpdateClass)

- (instancetype)init {
    self = [super init];
    
    if (self) {
    }
    ;
    return self;
}

- (void)loginFinish:(id)object {
    UserInfoModel *model    = object;
    NSString      *account  = [LOGINACCOUNT getObjectValue];
    NSString      *passWord = [LOGINPASSWORD getObjectValue];
    
    [KK_LastUser setObjectValue:model.user_id];
    [SN_PublicClass updateUser];
    SN_USER.portrait      = model.portrait;
    SN_USER.loginAccount  = account;
    SN_USER.loginPassword = passWord;
    SN_USER.is_first      = model.is_first;
    SN_USER.user_id       = model.user_id;
    SN_USER.access_token  = model.access_token;
    SN_USER.weight        = model.weight;
    SN_USER.height        = model.height;
    SN_USER.gender        = model.gender;
    SN_USER.job           = model.job;
    SN_USER.birthday      = model.birthday;
    SN_USER.target_step   = model.target_step;
    SN_USER.target_sleep  = model.target_sleep;
    [SN_USER updateToDB];
    NSLog(@"登陆成功>>>>>");
    // 登陆成功后跳转个人信息设置界面
    if (model.is_first == 1) {
        NSLog(@"设置个人信息界面>>>>>");
    } else {
        NSLog(@"进入主页 并获取用户信息>>>>");
        [SN_Net getUserInfoWithSuccess:^(id object) {
        } fail:^(id object) {
        }];
    }
    NSString *filePath = [[XYSandbox libCachePath] stringByAppendingPathComponent:KK_HeadImage];;
    NSData   *data     = [NSData dataWithContentsOfURL:[NSURL URLWithString:SN_USER.portrait]];
    [[NSFileManager defaultManager] createFileAtPath:filePath contents:data attributes:nil];
    
    [HASLOGIN setBOOLValue:YES];
    AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
    [app enterMainVc];
}

// 第三方登录 或者游客登录
- (void)loginOnWithOpenId:(NSString *)openId withOpenType:(NSString *)openType Success:(NSObjectSimpleBlock)success fail:(NSObjectSimpleBlock)fail {
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSDictionary         *dic     = @{@"openid":openId, @"opentype":openType};
    NSString             *url     = @"/user/open";
    
    [manager POST:url parameters:dic success:^(NSURLSessionDataTask *_Nonnull task, id _Nonnull responseObject)
     {
         if (responseObject[@"ret"] && [responseObject[@"ret"] intValue] == 0) {
             NSDictionary *dic = [responseObject objectForKey:@"data"];
             UserInfoModel *model = [UserInfoModel parseString:dic.YYJSONString];
             if (success) {
                 success(model);
             }
         } else {
             SHOWMBProgressHUD(nil, HHH_Text(responseObject[@"message"]), nil, NO, 2.0);
         }
     }    failure  :^(NSURLSessionDataTask *_Nullable task, NSError *_Nonnull error) {
         SHOWMBProgressHUD(nil, HHH_Text([error localizedDescription]), nil, NO, 2.0);
         if (fail) {
             fail(nil);
         }
     }];
}

// 登陆接口
- (void)loginOnWithsuccess:(NSObjectSimpleBlock)success fail:(NSObjectSimpleBlock)fail {
    NSString *account     = [LOGINACCOUNT getObjectValue];
    NSString *passWord    = [LOGINPASSWORD getObjectValue];
    NSString *passWordMd5 = @"";
    
    if (passWord) {
        passWordMd5 = [self md5:passWord];
    }
    NSDictionary *dict = [NSDictionary dictionary];
    if ([account contains:@"@"]) {
        dict = @{@"email":account,
                 @"password":passWordMd5};
    } else {
        dict = @{@"phone":account,
                 @"password":passWordMd5,
                 @"country_code":@"86"};
    }
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSString             *url     = @"/user/login";
    [manager POST:url parameters:dict success:^(NSURLSessionDataTask *_Nonnull task, id _Nonnull responseObject)
     {
         if (responseObject[@"ret"] && [responseObject[@"ret"] intValue] == 0) {
             NSDictionary *dic = [responseObject objectForKey:@"data"];
             UserInfoModel *model = [UserInfoModel parseString:dic.YYJSONString];
             if (success) {
                 success(model);
             }
         } else {
             SHOWMBProgressHUD(nil, HHH_Text(responseObject[@"message"]), nil, NO, 2.0);
         }
     }    failure  :^(NSURLSessionDataTask *_Nullable task, NSError *_Nonnull error) {
         SHOWMBProgressHUD(nil, HHH_Text([error localizedDescription]), nil, NO, 2.0);
         if (fail) {
             fail(nil);
         }
     }];
}

//用户信息反馈
- (void)FeedBackWithContent:(NSString *)content Success:(NSObjectSimpleBlock)success fail:(NSObjectSimpleBlock)fail {
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSString             *url     = @"/support/feedback2";
    NSDictionary         *dict    = @{@"access_token":SN_USER.access_token, @"content":content};
    
    [manager POST:url parameters:dict success:^(NSURLSessionDataTask *_Nonnull task, id _Nonnull responseObject)
     {
         success(responseObject);
     }    failure  :^(NSURLSessionDataTask *_Nullable task, NSError *_Nonnull error) {
         SHOWMBProgressHUD(nil, HHH_Text([error localizedDescription]), nil, NO, 2.0);
         if (fail) {
             fail(nil);
         }
     }];
}

//获取跑道信息
- (void)getTrackDataWithSuccess:(NSObjectSimpleBlock)success fail:(NSObjectSimpleBlock)fail {
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSString             *url     = @"/sport/track";
    NSDictionary         *dict    = @{@"access_token":SN_USER.access_token};
    
    [manager GET:url parameters:dict success:^(NSURLSessionDataTask *_Nonnull task, id _Nonnull responseObject)
     {
         if (responseObject[@"ret"] && [responseObject[@"ret"] intValue] == 0) {
             NSArray *arr = [responseObject objectForKey:@"data"];
             NSMutableArray *trackModelArr = [NSMutableArray array];
             for (NSDictionary *dic in arr) {
                 TrackModel *model = [TrackModel initWithDic:dic];
                 [trackModelArr addObject:model];
             }
             success(trackModelArr);
         }
     }   failure   :^(NSURLSessionDataTask *_Nullable task, NSError *_Nonnull error) {
         if (fail) {
         }
     }];
}

// 获取用户信息 token
- (void)getUserInfoWithSuccess:(NSObjectSimpleBlock)success fail:(NSObjectSimpleBlock)fail {
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSString             *url     = @"/user/view2";
    NSDictionary         *dict    = @{@"access_token":SN_USER.access_token, @"phone_uuid":[UIDevice currentDevice].identifierForVendor.UUIDString};
    
    NSLog(@"dict>>>>%@", dict);
    
    [manager GET:url parameters:dict success:^(NSURLSessionDataTask *_Nonnull task, id _Nonnull responseObject)
     {
         if (responseObject[@"ret"] && [responseObject[@"ret"] intValue] == 0) {
             NSDictionary *dic = [responseObject objectForKey:@"data"];
             UserInfoModel *model = [UserInfoModel parseString:dic.YYJSONString];
             if (success) {
                 success(model);
             }
             SN_USER.weight = [dic[@"weight"] floatValue];
             SN_USER.height = [dic[@"height"] integerValue];
             SN_USER.gender = [dic[@"gender"] integerValue];
             SN_USER.birthday = dic[@"birthday"];
             SN_USER.target_step = [dic[@"target_step"] integerValue];
             SN_USER.target_sleep = [dic[@"target_sleep"] integerValue];
             SN_USER.nickName = dic[@"nickname"];
             SN_USER.weightTime = dic[@"last_weight_time"];
             SN_USER.portrait = dic[@"portrait"];
             SN_USER.create_time = dic[@"create_time"];
             SN_USER.sport_days = [dic[@"sport_days"] integerValue];
             [[FileModelEntity sharedInstance] syncDataFromServer];
             // 蓝牙部分
             NSDictionary *lastDeviceDic = dic[@"last_device"];
             NSLog(@"lastDeviceDic>>>>>%@", lastDeviceDic);
             
             if (![lastDeviceDic isEqual:[NSNull null]]) {
                 NSString *lastUuid = lastDeviceDic[@"uuid"];
                 if (lastUuid.length > 0) {
                     [KK_BLELastDevice setObjectValue:lastDeviceDic[@"uuid"]];
                     [KK_BLELastChip setObjectValue:lastDeviceDic[@"adv_service"]];
                 }
             }
             if (![lastDeviceDic isEqual:[NSNull null]]) {
                 if ([lastDeviceDic[@"adv_id"]integerValue] > 0) {
                     SN_USER.updateBleAdv = [lastDeviceDic[@"adv_id"]integerValue];
                     [LASTCONNECTBLEHEAD setIntValue:SN_USER.updateBleAdv];
                 }
             }
             
             if (![lastDeviceDic isEqual:[NSNull null]]) {
                 if ([lastDeviceDic[@"mac"]integerValue] > 0) {
                     [KK_BLELastDeviceMac setObjectValue:lastDeviceDic[@"mac"]];
                 }
             }
             
             NSString *filePath = [[XYSandbox libCachePath] stringByAppendingPathComponent:KK_HeadImage];;
             NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:SN_USER.portrait]];
             [[NSFileManager defaultManager] createFileAtPath:filePath contents:data attributes:nil];
             [SN_USER updateToDB];
             
             [SN_Net getDeviceSFromServerWithSuccess:nil fail:nil];
         }
     }   failure   :^(NSURLSessionDataTask *_Nullable task, NSError *_Nonnull error) {
         if (fail) {
             fail(nil);
         }
     }];
}

//上传图片
- (void)uploadImageWithImage:(UIImage *)image WithSuccess:(NSObjectSimpleBlock)success fail:(NSObjectSimpleBlock)fail {
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSString             *url     = @"/user/upload-image";
    
    [manager POST:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
        NSString *fileName = [NSString stringWithFormat:@"%@.jpg", [[NSDate date] dateToString]];
        
        //上传的参数(上传图片，以文件流的格式)
        [formData appendPartWithFileData:imageData
                                    name:@"image"
                                fileName:fileName
                                mimeType:@"image/jpeg"];
    } success:^(NSURLSessionDataTask *_Nonnull task, id _Nonnull responseObject) {
        if (responseObject[@"ret"] && [responseObject[@"ret"] intValue] == 0) {
            NSArray *arr = responseObject[@"data"][@"urls"];
            SN_USER.portrait = arr.firstObject;
            success(arr);
        } else {
            SHOWMBProgressHUD(nil, responseObject[@"message"], nil, NO, 2);
        }
    } failure:^(NSURLSessionDataTask *_Nullable task, NSError *_Nonnull error) {
        SHOWMBProgressHUD(nil, HHH_Text([error localizedDescription]), nil, NO, 2.0);
    }];
}

// 上传用户信息 //1 昵称
- (void)updateUserInfoWithSuccess:(NSObjectSimpleBlock)success fail:(NSObjectSimpleBlock)fail {
    NSDictionary *userDic = @{@"nickname" : SN_USER.nickName ? SN_USER.nickName : @"",
                              @"birthday" :SN_USER.birthday,
                              @"height" : StrByInt(SN_USER.height ? SN_USER.height : 175),
                              @"weight" : SN_USER.weight ? @(SN_USER.weight) : @(70),
                              @"gender" : StrByInt(SN_USER.gender),
                              @"portrait" : SN_USER.portrait ? SN_USER.portrait : @"",
                              @"target_step" : StrByInt(SN_USER.target_step ? SN_USER.target_step : 10000),
                              @"target_sleep" : StrByInt(SN_USER.target_sleep ? SN_USER.target_sleep : 640),
                              @"last_weight_time" : [SN_USER.weightTime isEqualToString:@""] ? [[NSDate date] dateToDayString] : SN_USER.weightTime,
                              @"access_token" : SN_USER.access_token};
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSString             *url     = @"/user/update";
    
    [manager POST:url parameters:userDic success:^(NSURLSessionDataTask *_Nonnull task, id _Nonnull responseObject)
     {
         if (responseObject[@"ret"] && [responseObject[@"ret"] intValue] == 0) {
             NSDictionary *dic = [responseObject objectForKey:@"data"];
             UserInfoModel *model = [UserInfoModel parseString:dic.YYJSONString];
             if (success) {
                 success(model);
             }
         } else {
             SHOWMBProgressHUD(nil, SN_Text(responseObject[@"message"]), nil, NO, 2.0);
         }
     }    failure  :^(NSURLSessionDataTask *_Nullable task, NSError *_Nonnull error) {
         SHOWMBProgressHUD(nil, SN_Text(error.localizedDescription), nil, NO, 2.0);
         if (fail) {
             fail(nil);
         }
     }];
}

// 注册手机
- (void)RegistratWithPhonesuccess:(NSObjectSimpleBlock)success fail:(NSObjectSimpleBlock)fail {
    NSString     *passWordMd5 = [self md5:[LOGINPASSWORD getObjectValue]];
    NSDictionary *dict        = @{
                                  @"phone":[LOGINACCOUNT getObjectValue], @"password":passWordMd5,
                                  @"code":[LOGINCODE getObjectValue], @"country_code":[LOGINAREA getObjectValue]
                                  };
    // 开始注册
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSString             *url     = @"/user/signup";
    
    [manager POST:url parameters:dict success:^(NSURLSessionDataTask *_Nonnull task, id _Nonnull responseObject)
     {
         if (responseObject[@"ret"] && [responseObject[@"ret"] intValue] == 0) {
             //             SHOWMBProgressHUD(SN_Text(@"login was successful"), nil, nil, NO, 2.0);
             NSDictionary *dic = [responseObject objectForKey:@"data"];
             UserInfoModel *model = [UserInfoModel parseString:dic.YYJSONString];
             if (success) {
                 success(model);
             }
         } else {
             //             SHOWMBProgressHUD(nil, SN_Text(responseObject[@"message"]), nil, NO, 2.0);
         }
     }    failure  :^(NSURLSessionDataTask *_Nullable task, NSError *_Nonnull error) {
         if (fail) {
             fail(nil);
         }
     }];
}

// 注册邮箱
- (void)RegistratWithEmailsuccess:(NSObjectSimpleBlock)success fail:(NSObjectSimpleBlock)fail {
    NSString     *passWordMd5 = [self md5:[LOGINPASSWORD getObjectValue]];
    NSDictionary *dict        = @{
                                  @"email":[LOGINACCOUNT getObjectValue], @"password":passWordMd5,
                                  @"code":[LOGINCODE getObjectValue]
                                  };
    
    NSLog(@"dict>>>>>>>>>>>>%@", dict);
    
    // 邮箱开始注册
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSString             *url     = @"/user/signup";
    
    [manager POST:url parameters:dict success:^(NSURLSessionDataTask *_Nonnull task, id _Nonnull responseObject)
     {
         if (success) {
             success(responseObject);
         }
     }    failure  :^(NSURLSessionDataTask *_Nullable task, NSError *_Nonnull error) {
         if (fail) {
             fail(nil);
         }
     }];
}

// 获取设备在线信息
- (void)getDeviceSFromServerWithSuccess:(NSObjectSimpleBlock)success fail:(NSObjectSimpleBlock)fail {
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSString             *url     = @"/support/devices";
    [manager POST:url parameters:nil success:^(NSURLSessionDataTask *_Nonnull task, id _Nonnull responseObject)
     {
         if (responseObject[@"ret"] && [responseObject[@"ret"] intValue] == 0) {
             NSDictionary *dic = [responseObject objectForKey:@"data"];
             
             NSMutableArray *arr = [NSMutableArray array];
             for (NSDictionary *dic in responseObject[@"data"]) {
                 NSString *nameStr = dic[@"device_name"];
                 if (![arr containsObject:nameStr]) {
                     [arr addObject:nameStr];
                 }
             }
             [[NSUserDefaults standardUserDefaults] setObject:arr forKey:@"DeviceNameArr"];
             [[NSUserDefaults standardUserDefaults] synchronize];
             NSString *function = @"";
             for (NSDictionary *dic in responseObject[@"data"]) {
                 if ([[dic valueForKey:@"adv_id"]integerValue] == SN_USER.updateBleAdv) {
                     function = [dic valueForKey:@"function"];
                     KK_BLEModel.function = function.integerValue;
                     break;
                 }
             }
             
             for (NSDictionary *dic in responseObject[@"data"]) {
                 NSString *nameStr = dic[@"device_name"];
                 if ([KK_BLEModel.bleName isEqualToString:nameStr]) {
                     NSInteger Number = [LASTCONNECTBLEHEAD getIntValue];
                     NSInteger serviceNumber = [dic[@"adv_id"]integerValue];
                     NSLog(@"广播包>>>>>>%d 服务器>>>%d", Number, serviceNumber);
                     NSInteger customid = [dic[@"customid"]integerValue];
                     if (Number == 0) {
                         Number = serviceNumber;
                     }
                     if (SN_USER.updateBleCustomerID == 0) {
                         if (customid > 0) {
                             SN_USER.updateBleCustomerID = customid;
                             KK_BLEModel.bleCustomerID = customid;
                         }
                     }
                     [KK_BLEConfig updateService:(int)Number];
                     // 这里应该刷新>>>>>>
                     break;
                 }
             }
             [KK_BLEModel updateToDB];
             if (success) {
                 success(dic);
             }
             [SN_Net updateBleDeviceSuccess:^(id object) {
             } fail:^(id object) {
             }];
         } else {
         }
     }    failure  :^(NSURLSessionDataTask *_Nullable task, NSError *_Nonnull error) {
         if (fail) {
             fail(nil);
         }
     }];
}

// 获取设备升级信息
- (void)getDeviceUpdateInfoFromServerWithSuccess:(NSObjectSimpleBlock)success fail:(NSObjectSimpleBlock)fail {
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSString             *url     = @"/support/hwversion2";
    NSDictionary         *param   = @{@"adv_id":@(KK_BLEModel.bleAdvID), @"customid":@(1)};
//    KK_BLEModel.bleCustomerID
    [manager GET:url parameters:param success:^(NSURLSessionDataTask *_Nonnull task, id _Nonnull responseObject)
     {
         if (responseObject[@"ret"] && [responseObject[@"ret"] intValue] == 0) {
             NSDictionary *dic = [responseObject objectForKey:@"data"];
             KK_BLEModel.bleOnlineVersion = [dic[@"version"] integerValue];
             KK_BLEModel.download_url = dic[@"download_url"];
             KK_BLEModel.chip = [dic[@"chip"] lowercaseString];
             NSLog(@"KK_BLEModel.bleOnlineVersion===%ld,KK_BLEModel.download_url==%@", KK_BLEModel.bleOnlineVersion, KK_BLEModel.download_url);
             [KK_BLEModel updateToDB];
             success(nil);
         } else {
         }
     }   failure   :^(NSURLSessionDataTask *_Nullable task, NSError *_Nonnull error) {
         if (fail) {
             fail(nil);
         }
     }];
}

//获取所有APP版本状态
- (void)getAppUpdateInfoFromServerWithSuccess:(NSObjectSimpleBlock)success fail:(NSObjectSimpleBlock)fail {
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSString             *url     = @"/support/appversion2";
    
    [manager GET:url parameters:nil success:^(NSURLSessionDataTask *_Nonnull task, id _Nonnull responseObject)
     {
         if (responseObject[@"ret"] && [responseObject[@"ret"] intValue] == 0) {
             NSArray *arr = [responseObject objectForKey:@"data"];
             NSDictionary *dic = arr[1];
             SN_USER.lastOnlineAppVersion = [NSString stringWithFormat:@"%.2f", [dic[@"version_code"] floatValue]/100];
             success(nil);
         } else {
         }
     }   failure   :^(NSURLSessionDataTask *_Nullable task, NSError *_Nonnull error) {
         if (fail) {
             fail(nil);
         }
     }];
}

- (void)updateEveryModelWithType:(HJUpdateModelUpdateState)type {
    NSArray *array;
    
    if (type == HJUpdateStep) {
        array = [SNEveryDayModelHelp getModelWithOutUpdateFromLocalDBStep];
        if (array.count == 0) {
            [self updateDataWithType:type];
        } else {
            [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(updateHistoryStep) object:nil];
            [self performSelector:@selector(updateHistoryStep) withObject:nil afterDelay:10.0];
        }
    }
    
    if (type == HJUpdateSleep) {
        array = [SNEveryDayModelHelp getModelWithOutUpdateFromLocalDBSleep];
        if (array.count == 0) {
            [self updateDataWithType:type];
        } else {
            [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(updateHistorySleep) object:nil];
            [self performSelector:@selector(updateHistorySleep) withObject:nil afterDelay:10.0];
        }
    }
    
    if (type == HJUpdateHeart) {
        if (!SN_USER.heart) {
            return;
        }
        array = [SNEveryDayModelHelp getModelWithOutUpdateFromLocalDBHeart];
        if (array.count == 0) {
            [self updateDataWithType:type];
        } else {
            [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(updateHistoryHeart) object:nil];
            [self performSelector:@selector(updateHistoryHeart) withObject:nil afterDelay:10.0];
        }
    }
    
    if (type == HJUpdateOX) {
        if (!SN_USER.oxygen) {
            return;
        }
        array = [SNEveryDayModelHelp getModelWithOutUpdateFromLocalDBOx];
        if (array.count == 0) {
            [self updateDataWithType:type];
        } else {
            [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(updateHistoryOX) object:nil];
            [self performSelector:@selector(updateHistoryOX) withObject:nil afterDelay:10.0];
        }
    }
    
    if (type == HJUpdateBp) {
        if (!SN_USER.bistoryPressure) {
            return;
        }
        array = [SNEveryDayModelHelp getModelWithOutUpdateFromLocalDBBp];
        if (array.count == 0) {
            [self updateDataWithType:type];
        } else {
            [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(updateHistoryBp) object:nil];
            [self performSelector:@selector(updateHistoryBp) withObject:nil afterDelay:10.0];
        }
    }
}

- (void)updateHistoryStep {
    NSArray    *array = [SNEveryDayModelHelp getModelWithOutUpdateFromLocalDBStep];
    SportModel *model = [array firstObject];
    
    if (array.count > 0) {  // 先把本地数据昨天之前的数据都上传到服务器
        [self updateSport:model success:^(id object) {
        } fail:^(id object) {
        }];
        [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(updateHistoryStep) object:nil];
        [self performSelector:@selector(updateHistoryStep) withObject:nil afterDelay:5.0];
    }
    if (array.count == 0) {
        [self updateDataWithType:HJUpdateStep];
    }
}

- (void)updateHistorySleep {
    NSArray    *array = [SNEveryDayModelHelp getModelWithOutUpdateFromLocalDBSleep];
    SleepModel *model = [array firstObject];;
    
    if (array.count > 0) { // 先把本地数据昨天之前的数据都上传到服务器
        [self updateSleep:model success:^(id object) {
        } fail:^(id object) {
        }];
        [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(updateHistorySleep) object:nil];
        [self performSelector:@selector(updateHistorySleep) withObject:nil afterDelay:5.0];
    }
    if (array.count == 0) {
        [self updateDataWithType:HJUpdateSleep];
    }
}

- (void)updateHistoryHeart {
    NSArray    *array = [SNEveryDayModelHelp getModelWithOutUpdateFromLocalDBHeart];
    HeartModel *model = [array firstObject];
    
    if (array.count > 0) { // 先把本地数据昨天之前的数据都上传到服务器
        [self updateHeart:model success:^(id object) {
        } fail:^(id object) {
        }];
        [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(updateHistoryHeart) object:nil];
        [self performSelector:@selector(updateHistoryHeart) withObject:nil afterDelay:5.0];
    }
    if (array.count == 0) {
        [self updateDataWithType:HJUpdateHeart];
    }
}

- (void)updateHistoryOX {
    NSArray *array = [SNEveryDayModelHelp getModelWithOutUpdateFromLocalDBOx];
    OxModel *model = [array firstObject];;
    
    if (array.count > 0) { // 先把本地数据昨天之前的数据都上传到服务器
        [self updateOx:model success:^(id object) {
        } fail:^(id object) {
        }];
        [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(updateHistoryOX) object:nil];
        [self performSelector:@selector(updateHistoryOX) withObject:nil afterDelay:5.0];
    }
    if (array.count == 0) {
        [self updateDataWithType:HJUpdateOX];
    }
}

- (void)updateHistoryBp {
    NSArray *array = [SNEveryDayModelHelp getModelWithOutUpdateFromLocalDBBp];
    BpModel *model = [array firstObject];;
    
    if (array.count > 0) { // 先把本地数据昨天之前的数据都上传到服务器
        [self updateBp:model success:^(id object) {
        } fail:^(id object) {
        }];
        [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(updateHistoryBp) object:nil];
        [self performSelector:@selector(updateHistoryBp) withObject:nil afterDelay:5.0];
    }
    if (array.count == 0) {
        [self updateDataWithType:HJUpdateBp];
    }
}

- (void)updateDataWithType:(HJUpdateModelUpdateState)type {
    EveryDayModel  *model  = SN_PublicClass.todaymodel;
    NSUserDefaults *sss    = [NSUserDefaults standardUserDefaults];
    NSString       *stepS  = [sss valueForKey:[NSString stringWithFormat:@"%@step", model.dateString]];
    NSString       *sleepS = [sss valueForKey:[NSString stringWithFormat:@"%@sleep", model.dateString]];
    NSString       *heartS = [sss valueForKey:[NSString stringWithFormat:@"%@heart", model.dateString]];
    NSString       *oxS    = [sss valueForKey:[NSString stringWithFormat:@"%@ox", model.dateString]];
    NSString       *bpS    = [sss valueForKey:[NSString stringWithFormat:@"%@bp", model.dateString]];
    
    if (type == HJUpdateStep) {
        if (SN_PublicClass.todaySport.step != stepS.integerValue) {
            [self updateSport:SN_PublicClass.todaySport success:^(id object) {
            } fail:^(id object) {
            }];
        }
    }
    if (type == HJUpdateSleep) {
        if (SN_PublicClass.todaySleep.durations != sleepS.integerValue) {
            [self updateSleep:SN_PublicClass.todaySleep success:^(id object) {
            } fail:^(id object) {
            }];
        }
    }
    if (type == HJUpdateHeart) {
        if (SN_PublicClass.todayHeart.heartAllValueArray.count != heartS.integerValue) {
            [self updateHeart:SN_PublicClass.todayHeart success:^(id object) {
            } fail:^(id object) {
            }];
        }
    }
    if (type == HJUpdateOX) {
        if (SN_PublicClass.todayOx.oxsuArrayAuto.count != oxS.integerValue) {
            [self updateOx:SN_PublicClass.todayOx success:^(id object) {
            } fail:^(id object) {
            }];
        }
    }
    if (type == HJUpdateBp) {
        if (SN_PublicClass.todayBp.bpSuArray.count != bpS.integerValue) {
            [self updateBp:SN_PublicClass.todayBp success:^(id object) {
            } fail:^(id object) {
            }];
        }
    }
}

- (void)updateSport:(SportModel *)model success:(NSObjectSimpleBlock)success fail:(NSObjectSimpleBlock)fail {
    NSDictionary *dataDict = @{@"step" : model.stepArray,
                               @"distance" :model.distanceArray,
                               @"cal" : model.calorArray};
    NSDictionary *dict = @{@"mac" : KK_BLEModel.bleMAC,
                           @"date" : model.dateString,
                           @"duration" : StrByInt(model.stepDuration),
                           @"step" : StrByInt(model.step),
                           @"distance" : StrByInt(model.distance),
                           @"calory" : StrByInt(model.calory),
                           @"data" : [dataDict YYJSONString]};
    
    if (SN_USER.access_token) {
        NSDictionary *upload = @{@"access_token" : SN_USER.access_token,
                                 @"data" : [@[dict] YYJSONString]};
        [self uploadDataToServer:HJUpdateStep dict:upload success:^(id object)
         {
             NSUserDefaults *sss = [NSUserDefaults standardUserDefaults];
             [sss setValue:StrByInt(model.step) forKey:[NSString stringWithFormat:@"%@step", object]];
             [sss synchronize];
             [LASTUPDATESTEP setObjectValue:object];
             if (success) {
                 success(object);
             }
         }                  fail:^(id object) {
         }];
    }
}

- (void)updateSleep:(SleepModel *)model success:(NSObjectSimpleBlock)success fail:(NSObjectSimpleBlock)fail {
    if (model.durations == 0) {
        return;
    }
    NSMutableArray *sleepData = [NSMutableArray array];
    for (SleepSubModel *sleepmodel in model.sleepsubArray) {
        NSDictionary *dic = @{@"startTime" :sleepmodel.substartTime,
                              @"endTime" : sleepmodel.subendTime,
                              @"sleepData" : sleepmodel.subsleepData};
        [sleepData addObject:dic];
    }
    NSDictionary *dict = @{@"mac" : KK_BLEModel.bleMAC,
                           @"date" : model.dateString,
                           @"duration" : StrByInt(model.durations),
                           @"deep" : StrByInt(model.deeps),
                           @"light" : StrByInt(model.lights),
                           @"sober" : StrByInt(model.sobers),
                           @"data" : [sleepData YYJSONString]};
    if (SN_USER.access_token) {
        NSDictionary *upload = @{@"access_token" : SN_USER.access_token,
                                 @"data" : [@[dict] YYJSONString]};
        [self uploadDataToServer:HJUpdateSleep dict:upload success:^(id object)
         {
             NSUserDefaults *sss = [NSUserDefaults standardUserDefaults];
             [sss setValue:StrByInt(model.durations) forKey:[NSString stringWithFormat:@"%@sleep", object]];
             [sss synchronize];
             [LASTUPDATESLEEP setObjectValue:object];
             if (success) {
                 success(object);
             }
         }                  fail:^(id object) {
         }];
    }
}

- (void)updateOx:(OxModel *)model success:(NSObjectSimpleBlock)success fail:(NSObjectSimpleBlock)fail {
    NSMutableArray *oxArray = [NSMutableArray array];
    
    for (oxSubModel *oxModel in model.oxsuArrayAuto) {
        if (oxModel.oxValue > 0) {
            NSDictionary *dic = @{@"time" :[oxModel.updateTime componentsSeparatedByString:@" "][1],
                                  @"value" : StrByInt(oxModel.oxValue)};
            [oxArray addObject:dic];
        }
    }
    if (oxArray.count == 0) {
        return;
    }
    NSDictionary *dict = @{@"type" : StrByInt(1),
                           @"max" : StrByInt(model.oxMax),
                           @"min" : StrByInt(model.oxMin),
                           @"average" :StrByInt(model.oxAve),
                           @"times" : StrByInt(oxArray.count),
                           @"data" : [oxArray YYJSONString],
                           @"date" : model.dateString,
                           @"mac" : KK_BLEModel.bleMAC};
    NSArray *array = [NSArray arrayWithObjects:dict, nil];
    if (SN_USER.access_token) {
        NSDictionary *upload = @{@"access_token" : SN_USER.access_token,
                                 @"type":StrByInt(1),
                                 @"data" : [array YYJSONString]};
        [self uploadDataToServer:HJUpdateOX dict:upload success:^(id object)
         {
             NSUserDefaults *sss = [NSUserDefaults standardUserDefaults];
             [sss setValue:StrByInt(model.oxsuArrayAuto.count) forKey:[NSString stringWithFormat:@"%@ox", object]];
             [sss synchronize];
             [LASTUPDATEOX setObjectValue:object];
             if (success) {
                 success(object);
             }
         }                  fail:^(id object) {
         }];
    }
}

- (void)updateBp:(BpModel *)model success:(NSObjectSimpleBlock)success fail:(NSObjectSimpleBlock)fail {
    NSMutableArray *bpArray = [NSMutableArray array];
    
    for (bpSubModel *bpModel in model.bpSuArray) {
        if (bpModel.SBPValue && bpModel.DBPValue) {
            NSDictionary *dic = @{@"time" :[bpModel.updateTime componentsSeparatedByString:@" "][1],
                                  @"systolic" : StrByInt(bpModel.SBPValue),
                                  @"diastolic" :StrByInt(bpModel.DBPValue)};
            [bpArray addObject:dic];
        }
    }
    if (bpArray.count == 0) {
        return;
    }
    int          ave   = (model.SBPAve + model.DBPAve) /2;
    NSDictionary *dict = @{@"type" : StrByInt(3),
                           @"max" : StrByInt(model.SBPAve),
                           @"min" : StrByInt(model.DBPAve),
                           @"average" :StrByInt(ave),
                           @"times" : StrByInt(model.bpSuArray.count),
                           @"data" : [bpArray YYJSONString],
                           @"date" : model.dateString,
                           @"mac" : KK_BLEModel.bleMAC};
    NSArray *array = [NSArray arrayWithObjects:dict, nil];
    if (SN_USER.access_token) {
        NSDictionary *upload = @{@"access_token" : SN_USER.access_token,
                                 @"type":StrByInt(3),
                                 @"data" : [array YYJSONString]};
        [self uploadDataToServer:HJUpdateBp dict:upload success:^(id object)
         {
             NSUserDefaults *sss = [NSUserDefaults standardUserDefaults];
             [sss setValue:StrByInt(model.bpSuArray.count) forKey:[NSString stringWithFormat:@"%@bp", object]];
             [sss synchronize];
             [LASTUPDATEBP setObjectValue:object];
             if (success) {
                 success(object);
             }
         }                  fail:^(id object) {
         }];
    }
}

//1：血氧，2：心率，3：收缩压，4：舒展压
- (void)updateHeart:(HeartModel *)model success:(NSObjectSimpleBlock)success fail:(NSObjectSimpleBlock)fail {
    NSMutableArray *heartAuto  = [NSMutableArray arrayWithArray:model.heartsuArrayAuto];
    NSMutableArray *heartCheck = [NSMutableArray arrayWithArray:model.heartSuArrayCheck];
    NSMutableArray *heartArray = [NSMutableArray array];
    
    for (int k = 0; k < heartAuto.count; k++) {
        heartSubModel *heartModel = [heartAuto objectAtIndex:k];
        if (heartModel.heartValue > 0) {
            NSDictionary *dic = @{@"time" :[heartModel.updateTime componentsSeparatedByString:@" "][1],
                                  @"value" : StrByInt(heartModel.heartValue)
                                  , @"type":@"1"};
            [heartArray addObject:dic];
        }
    }
    for (int k = 0; k < heartCheck.count; k++) {
        heartSubModel *heartModel = [heartCheck objectAtIndex:k];
        if (heartModel.heartValue > 0) {
            NSDictionary *dic = @{@"time" :[heartModel.updateTime componentsSeparatedByString:@" "][1],
                                  @"value" : StrByInt(heartModel.heartValue)
                                  , @"type":@"0"};
            [heartArray addObject:dic];
        }
    }
    if (heartArray.count == 0) {
        return;
    }
    NSLog(@"heartArray>>>>>%@", heartArray);
    NSDictionary *dict = @{@"type" : StrByInt(2),
                           @"max" : StrByInt(model.heartMax),
                           @"min" : StrByInt(model.heartMin),
                           @"average" :StrByInt(model.heartAve),
                           @"times" : StrByInt(heartArray.count),
                           @"data" : [heartArray YYJSONString],
                           @"date" : model.dateString,
                           @"mac" : KK_BLEModel.bleMAC};
    NSArray *array = [NSArray arrayWithObjects:dict, nil];
    if (SN_USER.access_token) {
        NSDictionary *upload = @{@"access_token" : SN_USER.access_token,
                                 @"type":StrByInt(2),
                                 @"data" : [array YYJSONString]};
        [self uploadDataToServer:HJUpdateHeart dict:upload success:^(id object)
         {
             NSUserDefaults *sss = [NSUserDefaults standardUserDefaults];
             [sss setValue:StrByInt(model.heartAllValueArray.count) forKey:[NSString stringWithFormat:@"%@heart", object]];
             [sss synchronize];
             [LASTUPDATEHEART setObjectValue:object];
             if (success) {
                 success(object);
             }
         }                  fail:^(id object) {
         }];
    }
}

// 上传
- (void)uploadDataToServer:(HJUpdateModelUpdateState)link dict:(NSDictionary *)dict
                   success:(NSObjectSimpleBlock)success
                      fail:(NSObjectSimpleBlock)fail {
    NSString *type = @"";
    NSString *url  = @"";
    
    if (link == HJUpdateStep) {
        url  = @"/sport/upload";
        type = @"运动数据";
    } else if (link == HJUpdateSleep) {
        url  = @"/sleep/upload";
        type = @"睡眠数据";
    } else if (link == HJUpdateHeart) {
        url  = @"/examination/uploadday";
        type = @"心率数据";
    } else if (link == HJUpdateOX) {
        url  = @"/examination/uploadday";
        type = @"血氧数据";
    } else if (link == HJUpdateBp) {
        url  = @"/examination/uploadday";
        type = @"血压数据";
    }
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager POST:url parameters:dict success:^(NSURLSessionDataTask *_Nonnull task, id _Nonnull responseObject)
     {
         NSLog(@" AFHTTPSessionManager type:%@ JSON: %@", type, responseObject);
         NSDictionary *dic = [responseObject objectForKey:@"data"];
         NSArray *array = [dic valueForKey:@"success_dates"];
         NSString *sss = @"";
         if (array) {
             sss = [array firstObject];
         }
         [SN_PublicClass writefileWith:[NSString stringWithFormat:@"日期:%@ 类型:%@ 上传成功", sss, type]];
         if (success) {
             success(sss);
         }
     }    failure  :^(NSURLSessionDataTask *_Nullable task, NSError *_Nonnull error)
     {
         [SN_PublicClass writefileWith:[NSString stringWithFormat:@"上传失败:%@ 类型:%@", [error localizedDescription], type]];
     }];
}

- (void)uploadDataToServer:(NSString *)link dict:(NSDictionary *)dict image:(UIImage *)image imageName:(NSString *)imageName success:(NSObjectSimpleBlock)success fail:(NSObjectSimpleBlock)fail {
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    [manager POST:link parameters:dict constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        NSData *data = UIImagePNGRepresentation(image);
        NSString *fileName = imageName;
        [formData appendPartWithFileData:data name:@"track_image" fileName:fileName mimeType:@"image/png"];
    }
          success:^(NSURLSessionDataTask *_Nonnull task, id _Nonnull responseObject) {
              NSLog(@"responseObject===%@", responseObject);
          }
          failure:^(NSURLSessionDataTask *_Nullable task, NSError *_Nonnull error) {
              NSLog(@"error===%@", [error localizedDescription]);
          }];
}

//上传用户手环信息 先上传用户手环信息 再更新用户信息...
- (void)updateBleDeviceSuccess:(NSObjectSimpleBlock)success fail:(NSObjectSimpleBlock)fail {
    NSDictionary *dict = @{@"access_token":SN_USER.access_token, @"mac":[KK_BLELastDeviceMac getObjectValue] ? [KK_BLELastDeviceMac getObjectValue] : @"", @"device_name":KK_BLEModel.bleName ? KK_BLEModel.bleName : @"", @"adv_id":StrByInt(SN_USER.updateBleAdv) ? StrByInt(SN_USER.updateBleAdv) : @"", @"function":StrByInt(KK_BLEModel.function) ? StrByInt(KK_BLEModel.function) : @"", @"uuid":[KK_BLELastDevice getObjectValue] ? [KK_BLELastDevice getObjectValue] : @"", @"adv_service":[KK_BLELastChip getObjectValue] ? [KK_BLELastChip getObjectValue] : @""};
    // 开始注册
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSString             *url     = @"/user/userdevice";
    
    [manager POST:url parameters:dict success:^(NSURLSessionDataTask *_Nonnull task, id _Nonnull responseObject)
     {
         NSLog(@"上传用户手环信息>>>>>%@", responseObject);
         if (success) {
             success(responseObject);
         }
     }    failure  :^(NSURLSessionDataTask *_Nullable task, NSError *_Nonnull error)
     {
         if (fail) {
             fail(nil);
         }
     }];
}

//MD5加密
- (NSString *)md5:(NSString *)input {
    const char    *cStr = [input UTF8String];
    unsigned char digest[CC_MD5_DIGEST_LENGTH];
    
    CC_MD5(cStr, strlen(cStr), digest);   // This is the md5 call
    NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
        [output appendFormat:@"%02x", digest[i]];
    }
    return output;
}

- (void)uploadUserLog {
    NSArray *files = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[LogManager sharedInstance].basePath error:nil];
    
    files = [files sortedArrayUsingComparator:^NSComparisonResult (id _Nonnull obj1, id _Nonnull obj2) {
        return [obj2 compare:obj1];
    }];
    NSString *fileName = [NSString string];
    NSString *filePath = [NSString string];
    if (files.count == 1) {
        return;
    }
    for (int i = 0; i < files.count; i++) {
        if (i < files.count-1) {
            fileName = files[i+1];
            filePath = [NSString stringWithFormat:@"%@%@", [LogManager sharedInstance].basePath, fileName];
            AFHTTPSessionManager *manager    = [AFHTTPSessionManager manager];
            NSInteger            error_times = [[NSUserDefaults standardUserDefaults] integerForKey:fileName];
            NSString             *url        = @"/support/userlog";
            NSDictionary         *param      = @{@"access_token":SN_USER.access_token,
                                                 @"model":[NSString iphoneType],
                                                 @"brand":@"apple",
                                                 @"appversion":SN_USER.currentAppVersion,
                                                 @"apptype":@"2",
                                                 @"systemversion":[UIDevice currentDevice].systemVersion,
                                                 @"device_uuid":[UIDevice currentDevice].identifierForVendor.UUIDString,
                                                 @"date":[NSDate date].dateToDayString,
                                                 @"error_times":[NSString stringWithFormat:@"%ld", (long)error_times]};
            DEF_WEAKSELF_(SNUpdateClass)
            [manager POST:url parameters: param constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
                NSData *data = [NSData dataWithContentsOfFile:filePath];
                [formData appendPartWithFileData:data name:@"logfile" fileName:fileName mimeType:@"txt"];
            } success:^(NSURLSessionDataTask *_Nonnull task, id _Nonnull responseObject) {
                if (responseObject[@"ret"] && [responseObject[@"ret"] intValue] == 0) {
                    [[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
                    [weakSelf uploadUserLog];
                } else {
                    //SHOWMBProgressHUD(nil, responseObject[@"message"], nil, NO, 2);
                }
            } failure:^(NSURLSessionDataTask *_Nullable task, NSError *_Nonnull error) {
                //SHOWMBProgressHUD(nil, HHH_Text([error localizedDescription]), nil, NO, 2.0);
            }];
        } else {
            return;
        }
    }
}

- (void)feedBackUserLog {
    NSArray *files = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[LogManager sharedInstance].basePath error:nil];
    
    files = [files sortedArrayUsingComparator:^NSComparisonResult (id _Nonnull obj1, id _Nonnull obj2) {
        return [obj2 compare:obj1];
    }];
    NSString             *fileName = files.firstObject;
    NSString             *filePath = [NSString stringWithFormat:@"%@%@", [LogManager sharedInstance].basePath, fileName];
    AFHTTPSessionManager *manager  = [AFHTTPSessionManager manager];
    NSString             *url      = @"/support/userlog";
    NSDictionary         *param    = @{@"access_token":SN_USER.access_token,
                                       @"user_id":SN_USER.user_id,
                                       @"model":[NSString iphoneType],
                                       @"brand":@"apple",
                                       @"appversion":SN_USER.currentAppVersion,
                                       @"apptype":@"2",
                                       @"systemversion":[UIDevice currentDevice].systemVersion,
                                       @"device_uuid":[UIDevice currentDevice].identifierForVendor.UUIDString,
                                       @"date":[NSDate date].dateToDayString,
                                       @"error_times":[NSString stringWithFormat:@"%ld", (long)ErrorTimes]};
    
    [manager POST:url parameters:param constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        NSData *data = [NSData dataWithContentsOfFile:filePath];
        [formData appendPartWithFileData:data name:@"logfile" fileName:fileName mimeType:@"txt"];
    } success:^(NSURLSessionDataTask *_Nonnull task, id _Nonnull responseObject) {
        if (responseObject[@"ret"] && [responseObject[@"ret"] intValue] == 0) {
        } else {
            SHOWMBProgressHUD(nil, responseObject[@"message"], nil, NO, 2);
        }
    } failure:^(NSURLSessionDataTask *_Nullable task, NSError *_Nonnull error) {
    }];
}

@end

